﻿///<copyright>
/// Copyright © 2009 Stephen Styrchak. All Rights Reserved.
///</copyright>
using System;
using Microsoft.Xna.Framework;
using System.ComponentModel;

namespace Ferpect.ComponentModel
{
    public class TimerComponent : ControllerComponent
    {
        private float interval;
        private float elapsedMilliseconds;

        [Category("Behavior")]
        [Description("Occurs whenever the specified interval time has elapsed.")]
        public event EventHandler<EventArgs> Tick;

        public TimerComponent()
        {
            this.interval = 100f;
        }

        /// <summary>
        /// The number of milliseconds elapsed since the last Tick event. Before the first Tick
        /// event, it is the number of milliseconds elapsed since the timer was enabled. The time
        /// is elapsed game time, not elapsed real time.
        /// </summary>
        [Browsable(false)]
        public float ElapsedMilliseconds
        {
            get
            {
                return this.elapsedMilliseconds;
            }
        }

        [Category("Behavior")]
        [Description("The frequency of Tick events in milliseconds.")]
        [DefaultValue(100)]
        public int Interval
        {
            get { return (int)this.interval; }
            set
            {
                if (value <= 0)
                {
                    throw new ArgumentException(String.Format("Value '{0}' is not a valid value for Interval. Interval must be greater than 0.", value));
                }
                this.interval = value;
            }
        }

        /// <summary>
        /// Starts the timer.
        /// </summary>
        public void Start()
        {
            this.Enabled = true;
        }

        /// <summary>
        /// Stops the timer.
        /// </summary>
        public void Stop()
        {
            this.Enabled = false;
        }

        public override void Update(GameTime gameTime)
        {
            this.elapsedMilliseconds += (float)gameTime.ElapsedGameTime.TotalMilliseconds;
            if (this.elapsedMilliseconds >= this.interval)
            {
                if (this.Tick != null)
                {
                    this.Tick(this, EventArgs.Empty);
                }
                this.elapsedMilliseconds -= this.interval;
            }
        }
    }
}
